import axios from 'axios'
import Element from 'element-ui'
import router from './router'
import store from './store'


axios.defaults.baseURL = "http://localhost:8081"

// 前置拦截 发送请求时做的配置 可以在config中添加请求头的信息
axios.interceptors.request.use(config => {
  return config
})

// 后置拦截
axios.interceptors.response.use(response => {
    let res = response.data;

    console.log("=================")
    console.log(res)
    console.log("=================")

    if (res.code === 200) {
      return response
      //return Promise.resolve(response)
    } else {
      //elementUI中的错误消息弹窗
      Element.Message.error(res.msg, {duration: 3 * 1000})

      return Promise.reject(response.data.msg)
    }
  },
  error => {
    console.log(error)
    console.log(error.response.status)
    console.log(error.response.data)
    if(error.response.data) {
      error.message = error.response.data.msg
    }

    if(error.response.status === 401) {

    }

    // 这里是返回状态码不为200时候的错误处理
    if (error && error.response) {
      switch (error.response.status) {
        case 400:
          error.message = '请求错误'
          break

        case 401:
          error.message = '未授权，请登录'

          store.commit("REMOVE_INFO")
          router.push("/login")


        case 403:
          error.message = '拒绝访问'
          break

        case 404:
          error.message = `请求地址出错: ${err.response.config.url}`
          break

        case 408:
          error.message = '请求超时'
          break

        case 500:
          error.message = '服务器内部错误'
          break

        case 501:
          error.message = '服务未实现'
          break

        case 502:
          error.message = '网关错误'
          break

        case 503:
          error.message = '服务不可用'
          break

        case 504:
          error.message = '网关超时'
          break

        case 505:
          error.message = 'HTTP版本不受支持'
          break

        default:
      }
    }

    Element.Message.error(error.message, {duration: 3 * 1000})
    return Promise.reject(error)
  }
)
